<template>
  <div class="py-10 px-4 space-y-4">
    <!--<a-button type="primary" @click="handleOpenDB">连接数据库</a-button>-->
    <div>
      <div>
        <a-button @click="cursorGetData">通过游标查询数据（全部）</a-button>
      </div>
      <p class="mt-4"> 姓名： </p>
      <p class="mt-4">
        <a-input v-model:value="keyWord" />
      </p>
      <p>年龄：</p>
      <p class="flex">
        <a-input v-model:value="age" />
        <a-button type="primary" @click="handleAddData" class="ml-4">添加</a-button>
      </p>
    </div>

    <div class="flex space-x-3">
      <a-button type="primary" danger @click="handleDeleteSelected">删除</a-button>
    </div>
    <a-table
      :pagination="false"
      row-key="id"
      :row-selection="{
        selectedRowKeys,
        onChange: onSelectChange,
      }"
      :data-source="dataSource"
      :columns="[
        { title: '主键', dataIndex: 'id' },
        { title: '姓名', dataIndex: 'name' },
        { title: '年龄', dataIndex: 'age' },
      ]"
    />
    <div>
      <a-input-search
        placeholder="通过主键获取数据"
        v-model:value="enterById"
        @search="onSearchById"
      />
      <a-input-search class="mt-4" placeholder="通过索引查询数据" @search="getDataByIndex" />
      <a-input-search
        class="mt-4"
        placeholder="通过游标与索引组合查询数据"
        @search="cursorGetDataByIndex"
      />
      <a-input-group class="!mt-4">
        <a-select v-model:value="pageCurrent" style="margin-right: -1px">
          <a-select-option :value="1">第一页</a-select-option>
          <a-select-option :value="2">第二页</a-select-option>
        </a-select>
        <a-input-search
          style="width: calc(100% - 200px)"
          placeholder="分页查询"
          @search="cursorGetDataByIndexAndPage"
        />
      </a-input-group>
      <a-table
        class="mt-4"
        :data-source="dataSource2"
        :pagination="false"
        :columns="[
          { title: '主键', dataIndex: 'id' },
          { title: '姓名', dataIndex: 'name' },
          { title: '年龄', dataIndex: 'age' },
        ]"
      />
    </div>
  </div>
</template>

<script setup>
  import { ref } from 'vue';
  import { DB } from './db';

  const keyWord = ref('');
  const age = ref('');
  const dataSource = ref([]);
  const dataSource2 = ref([]);
  const imDb = new DB('IM', 1);

  imDb
    .open()
    .then(db => {
      console.log('连接成功');
      getAllData('user');
    })
    .catch(error => {
      console.error('连接失败', error);
    });

  async function getAllData() {
    const res = (await imDb.getAllData('user')) || [];
    dataSource.value = res;
  }

  async function handleAddData() {
    const data = {
      name: keyWord.value,
      age: age.value,
      id: Date.now(),
    };
    await imDb.addData('user', data);
    await getAllData();
    // .then(() => {
    //   alert('插入成功');
    // })
    // .catch(error => {
    //   console.error(error);
    // });
  }

  const enterById = ref('');

  async function onSearchById() {
    const res = await imDb.getDataById('user', enterById.value * 1);
    dataSource2.value = res ? [res] : [];
  }

  async function cursorGetData() {
    const res = await imDb.cursorGetData('user');
    console.log('通过游标查询数据结果：', res);
    dataSource2.value = res;
  }

  async function getDataByIndex(e) {
    const res = await imDb.getDataByIndex('user', 'age', e);
    console.log('通过索引查询数据结果：', res);
    res ? (dataSource2.value = [res]) : (dataSource2.value = []);
  }

  async function cursorGetDataByIndex(e) {
    const res = await imDb.cursorGetDataByIndex('user', 'age', e);
    console.log('通过索引和游标查询记录结果：', res);
    dataSource2.value = res;
  }

  const pageCurrent = ref(1);

  async function cursorGetDataByIndexAndPage(e) {
    try {
      const res = await imDb.cursorGetDataByIndexAndPage('user', 'age', e, pageCurrent.value, 5);
      console.log('分页查询结果：', res);
      dataSource2.value = res;
    } catch (error) {
      console.log(error);
    }
  }

  const selectedRowKeys = ref([]);

  function onSelectChange(keys, rows) {
    selectedRowKeys.value = keys;
  }

  // 删除选中的
  async function handleDeleteSelected() {
    await imDb.deleteDbByIds('user', selectedRowKeys.value);
    getAllData();
  }
</script>
